import React, {
  Component
} from 'react';
import { Table, Button, Input, Modal, notification, message } from 'antd';
import store from '../../../redux/index';
const Search = Input.Search;
import CreactFrom from '../CreactFrom/index.jsx';
import './index.less';
import axios from 'axios';
const confirm = Modal.confirm;

class MenuTable extends React.Component {
  state = {
    id: '',
    NumId: '',
    data: [],
    addFormVisible: false,
    formData: '',
    BtnsOff: ''

  }
  // 提示框
  openNotification = (type, Message, Description) => {
    notification[type]({
      message: Message,
      description: Description
    });
  };
  // 删除菜单单个资源
  deleteMenu = (ID, parentID) => {
    // console.log('ID:'+ID,"parentID:"+parentID);
    const Token = sessionStorage.getItem('token');
    const _this = this;
    axios.delete('/api/admin/element/' + ID, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      }
    })
      .then(function(response) {
        if (response.data.status == 200) {
          // _this.updataMenu("deleteOk");
          _this.openNotification('success', '成功', '删除成功');
          _this.getTableData(parentID);

        }

        // _this.clearValue(ID);

      })
      .catch(function(error) {
        console.log(error);
      });
  }

  showDeleteConfirm = (id) => {
    const _this = this;
    const parentID = this.props.ID;
    confirm({
      title: '删除',
      content: '此操作将永久删除，是否继续？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        _this.deleteMenu(id, parentID);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  ReviseResources =(id) => {
    this.setState({
      addFormVisible: true,
    });
    this.setState({
      NumId: id
    });
  }

  componentWillUpdate(nextProps, nextState) {
    if (this.state.id == nextProps.ID) {
      return false;
    } else {
      this.state.id = nextProps.ID;
      this.getTableData(nextProps.ID);
    }

  }

  // 获取菜单下表格数据
  getTableData = (ID) => {
    // console.log("更新成功："+ID)
    const Token = sessionStorage.getItem('token');
    const $this = this;
    axios({
      method: 'get',
      url: '/api/admin/element/list',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: { menuId: ID, name: '' }
    })
      .then(function (response) {
        console.log(response);
        let data = [];
        if (response.data.data.rows) {
          response.data.data.rows.forEach((item, i) => {
            data.push(item);
          });

          $this.setState({
            data: data
          });
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  }


  // 添加按钮或资源
  ResourcesCreate = (_this, eidtMenu) => {
    const $this = this;

    if (this.state.BtnsOff == 'eidtMenu') {
      // console.log("编辑请求");
      _this.props.form.validateFields((err, values) => {
        values.menuId = this.state.id;
        values.id = _this.state.id;
        if (!err) {
          const $this = this;
          const Token = sessionStorage.getItem('token');
          axios({
            method: 'put',
            url: '/api/admin/element/' + values.id,
            headers: {
              Authorization: Token
            },
            data: values
          })
            .then(function (response) {
              _this.openNotification('success', '成功', '编辑成功');
              _this.props.form.resetFields();
              $this.getTableData($this.state.id);
            })
            .catch(function (error) {
              console.log(error);
              message.error('服务器开小差啦，请重试！');
            });
        }
      });
    } else {
      // console.log("添加请求")
      if (this.state.id && this.state.BtnsOff == 'addMenu') {
        // console.log("添加请求-----"+this.state.id);
        _this.props.form.validateFields((err, values) => {
          values.menuId = this.state.id;
          if (!err) {
            const $this = this;
            const Token = sessionStorage.getItem('token');
            axios({
              method: 'post',
              url: '/api/admin/element',
              headers: {
                Authorization: Token
              },
              data: values
            })
              .then(function (response) {
                _this.openNotification('success', '成功', '添加成功');
                _this.props.form.resetFields();
                $this.getTableData($this.state.id);
              })
              .catch(function (error) {
                console.log(error);
                message.error('服务器开小差啦，请重试！');
              });
          }
        });
      } else {
        _this.openNotification('warning', '请选择菜单');
      }
    }

    this.setState({ addFormVisible: false });
  }

  showModal = () => {
    this.setState({
      addFormVisible: true,
      BtnsOff: 'addMenu'
    });
    store.dispatch({ type: 'DeleteValue', DeleteValue: true });
  }
  handleChancel = (_this) => {
    this.setState({
      addFormVisible: false,
    });
    _this.resetFields();
  }

  handleCreate = () => {
    this.setState({
      addFormVisible: false,
    });
  }
  render() {
    const columns = [{
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    }, {
      title: '资源编码',
      dataIndex: 'code',
      key: 'code',
    }, {
      title: '资源类型',
      dataIndex: 'type',
      key: 'type',
    }, {
      title: '资源名称',
      dataIndex: 'name',
      key: 'name',
    }, {
      title: '资源地址',
      dataIndex: 'uri',
      key: 'uri',
    }, {
      title: '资源请求类型',
      dataIndex: 'method',
      key: 'method',
    }, {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    }, {
      title: '操作',
      key: '操作',
      width: 140,
      render: (text, record) => (
        <div className="TableOperation">
          <Button type="primary" size="small" onClick={() => this.ReviseResources(record.id)}>编辑</Button>
          <Button type="danger" size="small" onClick={() => this.showDeleteConfirm(record.id)}>删除</Button>
        </div>
      ),
    }];

    return (
      <div className="TableList">
        <h3 className="TableTitle">按钮或资源</h3>
        <div className="btns">
          <Search placeholder="姓名或账户" enterButton size="large" style={{ width: 260 }} />
          <Button type="primary" size="large" icon="edit" onClick={this.showModal} className="add">添加</Button>
        </div>
        <Table columns={columns} dataSource={this.state.data} rowKey="id" bordered />
        <CreactFrom
          visible={this.state.addFormVisible}
          onCancel={this.handleChancel}
          onCreate={this.ResourcesCreate}
          NumId={this.state.NumId}
        />
      </div>

    );
  }
}

export default MenuTable;